import { Empty, Icon, Loading, PullToRefresh } from '@antmjs/vantui'
import { ProListProps } from './interface'

import { ScrollView, ScrollViewProps, View } from '@tarojs/components'
import { useEffect, useRef, useState } from 'react'
import Taro, { IntersectionObserver, nextTick } from '@tarojs/taro'

/**
 * 功能封装点：
 * 1. 初始化，自动发起请求
 * 2. 下拉刷新
 * 3. 下滑到底部自动请求下一页数据
 */
const ProList = ({
	data,
	height,
	reflesh,
	reload,
	getNextPage,
	isLastPage,
	loading,
	itemRender,
	error = false
}: ProListProps) => {
	const [isTop, setIsTop] = useState(false)
	const infiniteScrollInstance = useRef<IntersectionObserver | null>(null)
	const [bottomFlag, setBottomFlag] = useState(0)

	const onRefresh = async () => {
		await reflesh()
		return Promise.resolve(undefined)
	}
	const onScroll: ScrollViewProps['onScroll'] = e => {
		setIsTop(e.detail.scrollTop < 10)
	}

	const initObserver = () => {
		const currentpage = Taro.getCurrentInstance().page
		const io = Taro.createIntersectionObserver(currentpage || {})

		infiniteScrollInstance.current = io
		infiniteScrollInstance.current
			?.relativeToViewport()
			.observe('.footer', entrie => {
				if (entrie.intersectionRatio > 0) {
					setBottomFlag(Math.random())
				}
			})
	}
	// 初始化请求
	useEffect(() => {
		reload()
		nextTick(initObserver)
		return infiniteScrollInstance.current?.disconnect
	}, [])

	useEffect(() => {
		if (!isLastPage && bottomFlag) {
			getNextPage()
		}
	}, [bottomFlag, isLastPage])

	return (
		<View id='proListContainer'>
			<PullToRefresh onRefresh={onRefresh} disable={!isTop}>
				<ScrollView
					scrollY
					style={`height: ${height}`}
					showScrollbar={false}
					onScroll={onScroll}
				>
					{!data.length && <Empty />}
					{data?.map(item => itemRender?.(item))}
					<View
						className='footer'
						style={{
							display: 'flex',
							alignItems: 'center',
							justifyItems: 'center',
							paddingBlock: 8,
							textAlign: 'center',
							minHeight: 48
						}}
					>
						{loading && (
							<Loading
								type='spinner'
								size={48}
								style={{ display: 'flex', flex: 1 }}
							/>
						)}
						{isLastPage && (
							<View style={{ width: '100%' }}>已经是最后一页了</View>
						)}
						{error && (
							<View style={{ width: '100%', color: 'blue' }}>
								重新加载
								<Icon
									name='replay'
									size={32}
									onClick={reload}
									style={{ marginInlineStart: '8px' }}
								/>
							</View>
						)}
					</View>
				</ScrollView>
			</PullToRefresh>
		</View>
	)
}

export default ProList
